package com.docker.manege.image;

import com.alibaba.fastjson.JSONObject;
import com.docker.core.mvc.service.BaseService;
import com.docker.core.third.docker.DockerKit;
import com.docker.core.third.websocket.WebsocketCMD;
import com.docker.core.third.websocket.WebsocketPool;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.SearchItem;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Okv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import kit.docker.convert.RecordKit;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangbei
 * @date 2020/12/4 - 10:39
 */
public class ImagesService extends BaseService {

    @Inject
    private ImagesDao imagesDao;

    public List<Record> list(String clientKey, String imageName) {
        List<Record> result = new ArrayList<>();
        List<Image> images = DockerKit.images(clientKey, imageName);
        Record img;
        for (Image image : images) {
            img = new Record();
            img.set("image_id", image.getId());
            img.set("image_tags", image.getRepoTags());
            img.set("image_parent_id", image.getParentId());
            img.set("image_size", image.getSize());
//            img.set("create_time", DateKit.timestampFormat(image.getCreated(), DateStyle.YYYY_MM_DD_HH_MM_SS)); //时间戳
            result.add(img);
        }
        return result;
    }

    public List<SearchItem> search(String clientKey, String imageName) {
        return DockerKit.searchImage(clientKey, imageName);
    }

    public boolean pull(String clientKey, String connectKey, ImagesBean imagesBean, String userId) {
        Okv cond = Okv.create()
                .set("i.status_flag = ", "1")
                .set("i.server_id = ", imagesBean.getServer_id())
                .set("image_name", "'" + imagesBean.getImage_name() + "'" + " like image_name||'%'");
        Record image = imagesDao.info(Okv.by("cond", cond));
        if (StrKit.notNull(image)) {
            image.set("image_name", imagesBean.getImage_name());
            image.set("note", imagesBean.getNote());
            image.set("remark", "拉取镜像");
            image.set("update_time", getNowDateTime());
            image.set("update_oper_id", userId);
            return tx(() -> {
                if (!imagesDao.update(image)) {
                    throwError("镜像拉取失败");
                }
                return DockerKit.pullImage(clientKey, imagesBean.getImage_name(), connectKey);
            });
        }
        imagesBean.setRi_id(getUUID32());
        imagesBean.setStatus_flag("1");
        imagesBean.setRemark("新增镜像");
        imagesBean.setCreate_time(getNowDateTime());
        imagesBean.setCreate_oper_id(userId);
        imagesBean.setUpdate_time(imagesBean.getCreate_time());
        imagesBean.setUpdate_oper_id(imagesBean.getCreate_oper_id());
        return tx(() -> {
            if (!imagesDao.save(RecordKit.objectToRecord(imagesBean))) {
                throwError("镜像拉取失败");
            }
            return DockerKit.pullImage(clientKey, imagesBean.getImage_name(), connectKey);
        });
    }

    public boolean remove(String clientKey, String serverId, String imageId, String imageName, String force, String userId) {
        Okv cond = Okv.create()
                .set("i.status_flag = ", "1")
                .set("i.server_id = ", serverId)
                .set("image_name", "'" + imageName + "'" + " like image_name||'%'");
        Record image = imagesDao.info(Okv.by("cond", cond));
        if (!StrKit.notNull(image)) {
            return DockerKit.removeImage(clientKey, imageId, force);
        }
        image.set("status_flag", "0");
        image.set("remark", "删除镜像");
        image.set("update_time", getNowDateTime());
        image.set("update_oper_id", userId);
        return tx(() -> {
            if (!imagesDao.update(image)) {
                throwError("镜像删除失败");
            }
            return DockerKit.removeImage(clientKey, imageId, force);
        });
    }

    public Record detail(String serverId, String imageName) {
        Okv cond = Okv.create()
                .set("i.status_flag = ", "1")
                .set("i.server_id = ", serverId)
                .set("image_name", "'" + imageName + "'" + " like image_name||'%'");
        Record image = imagesDao.detail(Okv.by("cond", cond));
        if (!StrKit.notNull(image)) {
            throwError("未找到创建信息");
        }
        return image;
    }

    public void onMessage(WebsocketPool socketPool, JSONObject msgJson) {
        switch (msgJson.getString("cmd")) {
            case WebsocketCMD.CMD_IMAGE_PULL:
                sendMsg(socketPool.getConnect_key(), msgJson);
                break;
            default:
                //to do some thing
                break;
        }
    }

}
